package com.sea.demo.shiro.common;

import com.sea.demo.shiro.domain.User;
import com.sea.demo.shiro.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Objects;
import java.util.Set;

/**
 * @Author: 快乐在角落里
 * @Create: 2020/11/7 23:05
 * Shiro认证授权类
 */

public class ShiroRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    /** 授权 */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        User user = (User) principals.getPrimaryPrincipal();
        Set<String> roles = userService.selectRoleCodeSet(user.getId());
        Set<String> permissions = userService.selectPermissionCodeSet(user.getId());
        simpleAuthorizationInfo.setRoles(roles);
        simpleAuthorizationInfo.setStringPermissions(permissions);
        return simpleAuthorizationInfo;
    }

    /** 认证 */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String) token.getPrincipal();
        User user = userService.selectUserByUsername(username);
        if(Objects.isNull(user) || Objects.isNull(user.getPassword()) || Objects.isNull(user.getSalt())){
            throw new UnknownAccountException();
        }
        if(user.getState() == 0){
            /* 0:禁用 1:可用*/
            throw new LockedAccountException();
        }
        return new SimpleAuthenticationInfo
                (user, user.getPassword(), ByteSource.Util.bytes(user.getSalt()), this.getName());
    }
}
